import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:platform_service/src/scanner/scanner.dart';

///
/// @Author: yangjie
/// @Date: 2020/9/25 1:21 PM
/// @Description:
///

abstract class NDScannerPlatformCallbacksHandler {
  void onScanResult(String? result);

  /// 下面几个方法 H5模式 无指定扫码页面时调用
  Future Function() controllerDispose = () {
    return Future.value();
  };

  Future Function() start = () {
    return Future.value();
  };

  Future Function() stop = () {
    return Future.value();
  };

  Future Function() pause = () {
    return Future.value();
  };

  Future Function() resume = () {
    return Future.value();
  };
}

class NDMethodChannelScanner {
  final NDScannerPlatformCallbacksHandler _platformCallbacksHandler;

  late MethodChannel _channel;

  bool get isH5ScannerModel => kIsWeb && h5NDScannerPage == null;

  //id 如果一个页面有多个platformView,需要用id区分，此处没有使用
  NDMethodChannelScanner(int id, this._platformCallbacksHandler) {
    _channel = const MethodChannel("scanner");
    _channel.setMethodCallHandler(_onMethodCall);
  }

  Future<bool> _onMethodCall(MethodCall call) async {
    switch (call.method) {
      case 'onScanResult':
        final String? result = call.arguments['result'];
        _platformCallbacksHandler.onScanResult(result);
        return true;
    }
    throw MissingPluginException(
      '${call.method} was invoked but has no handler',
    );
  }

  Future<void> dispose() {
    if (isH5ScannerModel) {
      return _platformCallbacksHandler.controllerDispose.call();
    }
    return _channel.invokeMethod<void>('dispose');
  }

  Future<void> start() {
    if (isH5ScannerModel) {
      return _platformCallbacksHandler.start.call();
    }
    return _channel.invokeMethod<void>('start');
  }

  Future<void> stop() {
    if (isH5ScannerModel) {
      return _platformCallbacksHandler.stop.call();
    }
    return _channel.invokeMethod<void>('stop');
  }

  Future<void> pause() {
    if (isH5ScannerModel) {
      return _platformCallbacksHandler.pause.call();
    }
    return _channel.invokeMethod<void>('pause');
  }

  Future<void> resume() {
    if (isH5ScannerModel) {
      return _platformCallbacksHandler.resume.call();
    }
    return _channel.invokeMethod<void>('resume');
  }
}

class NDMethodQRCodeScanner {
  late MethodChannel _channel;

  NDMethodQRCodeScanner() {
    _channel =
        const MethodChannel("com.newcore.demo.flutter.plugin/qrcode/file");
  }

  Future getQrResult(List<String> paths) {
    return _channel.invokeMethod("ScanImage", {"path": paths});
  }
}
